package fr.axones.pocketagile.ui.controler.command.project
{	
	import fr.axones.pocketagile.services.remote.AuthenticationService;
	import fr.axones.pocketagile.services.remote.ProjectService;
	import fr.axones.pocketagile.ui.controler.Controler;
	import fr.axones.pocketagile.ui.model.Model;
	import fr.axones.pocketagile.ui.view.authentication.AuthenticationEvent;
	import fr.axones.pocketagile.ui.view.main.project.ProjectEvent;
	import fr.axones.pocketagile.vo.ProjectVO;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ProjectDeleteCommand
	{
		[Inject(id='projectService')]
		public var projectService:ProjectService;
		
		[Inject(id='controler')]
		public var controler:Controler;
		
		[Inject(id='model')]
		public var model:Model;
		
		public static const SUCCESS:String = "successDeleteProject";
		
		public static const ERROR_UNKNOW:String = "unknowDeleteProject";
		public static const ERROR_CONNECTION:String = "connectionDeleteProject";
		
		public function ProjectDeleteCommand()
		{
		}
		
		[Command(selector="deleteProject")]
		public function execute(event:ProjectEvent):AsyncToken
		{				
			controler.showWaitingPanel();
			return projectService.deleteProject(event.projectId);
		}
		
		[CommandResult(selector="deleteProject")]
		public function result(result:ResultEvent,event:ProjectEvent):void
		{		
			controler.hideWaitingPanel();
			
			if(result.result.status<300 && result.result.status>=200)
			{
				for (var i:int = 0; i<model.projects.length ; i++)
				{
					if((model.projects.getItemAt(i) as ProjectVO).id == event.projectId)
					{
						model.projects.removeItemAt(i);
					}
				}
				controler.throwSuccess(SUCCESS,result.result.data,result.result.status);
			}
			else
			{
				controler.throwError(ERROR_UNKNOW,null,1);
			}
		}
		
		[CommandError(selector="deleteProject")]
		public function fault(fault:FaultEvent,event:ProjectEvent):void
		{
			controler.hideWaitingPanel();
			controler.throwError(ERROR_CONNECTION,null,0);
		}
	}
}